package com.atguigu.fink.chapter01.timeattr;

import com.atguigu.fink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/11/28 15:09
 */
public class Flink02_TableApi_Time_Event {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("s1", 1000L, 10),
                new WaterSensor("s1", 2000L, 10),
                new WaterSensor("s2", 3000L, 20),
                new WaterSensor("s1", 4000L, 30),
                new WaterSensor("s1", 5000L, 40),
                new WaterSensor("s1", 6000L, 50)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
        
            );
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 1. 流转成表的时候添加事件时间
        // 1.1 新增一个字段表示事件时间
//        Table table = tEnv.fromDataStream(stream, $("id"), $("ts"), $("et").rowtime(), $("vc"));
        // 1.2 把现有的字段转成事件时间
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        table.printSchema();
        table.execute().print();
        
    }
}
